package com.example.demo.config;

import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author zhaiding
 * @since 2019/5/1
 */
@SpringBootConfiguration
@EnableAsync
public class ThreadConfig {

    @Bean
    public ThreadPoolTaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 设置ThreadPoolExecutor的核心池大小。 默认值为1。
        executor.setCorePoolSize(20);
        // 设置ThreadPoolExecutor的最大池大小。默认值 Integer.MAX_VALUE
        executor.setMaxPoolSize(100);
        // 设置ThreadPoolExecutor的保持活动秒数。 默认是60。
        executor.setKeepAliveSeconds(30000);
        // 为ThreadPoolExecutor的 BlockingQueue 设置容量。
        executor.setQueueCapacity(100);
        executor.setThreadNamePrefix("default_task_executor_thread");
        executor.initialize();
        //当任务数量超过MaxPoolSize和QueueCapacity时使用的策略，该策略是又调用任务的线程执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return executor;
    }
}
